<?php
/**
 * 私信群发功能
 * Date: 2020/7/9
 * Author: sunlinxin
 */
namespace Frieza\Modules\Im\Controllers;

use App\Admin\Extensions\Tools\UserButton;
use App\Pockets\GridDataModel as pGridDataModel;
use App\Http\Controllers\Controller;
use Doraemon\model\AdmMsgSendDetails;
use Doraemon\model\AdmMsgSendList;
use Doraemon\model\Ban;
use Doraemon\model\Member;
use Doraemon\service\position\PositionApi;
use Doraemon\tools\Log;
use Doraemon\model\Position\PositionRules;
use Doraemon\service\User;
use Doraemon\service\AdmMsgSend as sAdmMsgSend;
use Doraemon\cache\Im\AdmMsgSendTask;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;

class MsgSendController extends Controller
{
    public function __construct()
    {
        parent::__construct();
        Admin::script($this->addScript());
        Admin::style($this->addStyle());
    }

    /**
     * 任务列表视图
     * @param Request $request
     * @param Content $content
     * @return Content
     */
    public function index(Request $request, Content $content)
    {
        $params = $request->input();
        $condition['ORDER'] = ['id' => 'DESC'];
        $pageSize = $request->input("per_page", 10);
        $page = $request->input("page", 1);
        $condition['LIMIT'] = [
            ($page - 1) * $pageSize,
            $pageSize
        ];
        $search = [];
        if (isset($params['task_title']) && $params['task_title']) {
            $search["task_title[~]"] = $params['task_title'];
        }
        if (isset($params['send_status'])) {
            $search['send_status'] = intval($params['send_status']);
        }
        if (isset($params['send_user']) && $params['send_user']) {
            $search['send_user'] = $params['send_user'];
        }
        if (isset($params['admin_name']) && $params['admin_name']) {
            $adminIds = [];
            $adminData = Admin::user()->where('name', 'like', '%'.$params['admin_name'].'%')->get();
            foreach ($adminData as $val) {
                $adminIds[] = $val->id;
            }
            $search['admin_id'] = $adminIds;
        }
        if (isset($params['send_time']) && $params['send_time']) {
            if ($params['send_time']['start']) {
                $search['send_time[>]'] = strtotime($params['send_time']['start']);
            }
            if ($params['send_time']['end']) {
                $search['send_time[<]'] = strtotime($params['send_time']['end']);
            }
        }
        if ($search) $condition['AND'] = $search;
        $list = AdmMsgSendList::getMsgSendList($condition);
        foreach ($list['list'] as &$item) {
            $item['uid_num'] = AdmMsgSendTask::getUidCount($item['id']);
        }
        unset($item);

        $dataList = $list['list'] ?? [];
        $ids = array_column($dataList, 'id');
        $rules = PositionApi::activeRules($ids, PositionRules::MODULE_TYPE_MSG_SEND);
        $list['list'] = array_map(function ($v) use ($rules) {
            $v['userprofile'] = $rules[$v['id']] ?? [];
            return $v;
        }, $dataList);

        $gridModel = new pGridDataModel($list['list'], $list['total'], [
            'perPage' => $pageSize
        ]);
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->disableCreateButton();
                $grid->disableRowSelector();
                $grid->disableColumnSelector();
                $grid->disableExport();
                $grid->paginate(10);
                $grid->filter(function($filter){
                    // 去掉默认的id过滤器
                    $filter->disableIdFilter();
                    $filter->column(8, function ($filter) {
                        $filter->like('task_title', '任务标题');
                        $filter->equal('send_status', '发送状态')->radio(AdmMsgSendList::SEND_STATUS);
                        $user_list = Member::getUsers(User::getOfficeUidFromServerConf() ?: User::OFFICE_UID);
                        $from_users = [];
                        foreach ($user_list as $user) {
                            $from_users[$user['uid']] = $user['nick'];
                        }
                        $filter->equal('send_user', '发送人')->select($from_users);
                        $filter->like('admin_name', '操作人');
                    });
                    $filter->column(12, function ($filter) {
                        $filter->between('send_time', '发送时间')->datetime();
                    });
                });
                $grid->tools(function (Grid\Tools $tool) {
                    $tool->append(new UserButton(UserButton::TYPE_HREF, '', '新增任务', '', url('/admin/im/create')));
                });
                $grid->column('id', 'ID');
                $grid->column('task_title', '任务标题');
                $grid->column('send_time', '发送时间')->display(function () {
                    return date("Y-m-d H:i:s", $this->send_time);
                });
                $grid->column('send_status', '发送状态')->using(AdmMsgSendList::SEND_STATUS);
                $grid->column('send_user', '发送人')->display(function () {
                    $sendUserInfo = Member::getUserInfoNew($this->send_user);
                    return $sendUserInfo['nick'];
                });
                $grid->column('userprofile', '用户分群')->width(200)->userProfile();
                $grid->column('uid_num', '剩余用户数');
                $grid->column('to_user_num', '发送数');
                $grid->column('admin_id', '操作人')->display(function () {
                    return Admin::user()->find($this->admin_id)->name;
                });
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableEdit();
                    $actions->disableDelete();
                    $actions->append('<a href="/admin/im/view/' . $actions->row->id . '" class="fa fa-info-circle">查看详情</a>');
                    if (in_array($actions->row->send_status, [
                        AdmMsgSendList::SEND_STATUS_NO_START,
                        AdmMsgSendList::SEND_STATUS_ALREADY_DATA,
                        AdmMsgSendList::SEND_STATUS_ERR_DATA,
                        AdmMsgSendList::SEND_STATUS_FAILURE
                    ])) {
                        $actions->append('&nbsp;&nbsp;<a class="fa fa-trash cancel-send" data-id="' . $actions->row->id . '" href="javascript:void(0);">取消发送</a>');
                    }
                    if ($actions->row->send_status == AdmMsgSendList::SEND_STATUS_FAILURE && $actions->row->uid_num > 0) {
                        $actions->append('&nbsp;&nbsp;<a class="fa fa-inbox resend" data-id="' . $actions->row->id . '" href="javascript:void(0);">继续发送</a>');
                    }
                });
            });
        return $content
            ->header('私信群发')
            ->description('任务列表')
            ->breadcrumb(['text' => '私信群发'])
            ->body($gridList->render());
    }

    /**
     * 新增任务视图
     * @param Request $request
     * @param Content $content
     * @param int $id
     * @return Content
     */
    public function create(Request $request, Content $content, $id = 0)
    {
        if ($id) {
            Admin::script(<<<EOF
        $(function(){
            $("input[name='user_profile[is_all]']:first").parent().parent().remove();
        });
EOF
            );
        } else {
            Admin::script(<<<EOF
        $(function(){
            $("input[name='user_profile[is_all]']:first").parent().parent().remove();
            $("input[name='user_profile[is_all]']:last").parent().trigger('click');
        });
EOF
            );
        }
        $header = $id ? '查看' : '新增';
        $row = [];
        if ($id) {
            $row = sAdmMsgSend::getTaskInfo($id);
        }
        $form = new Form($row);
        $tab = new Tab();
        $tab->add($header, $form);
        $form->text('task_title', '任务标题')->required();
        if ($row) {
            $form->datetime('send_time', '发送时间')
                ->help('发送时间至少要大于当前时间半个小时「>30分钟」')->disable();
        } else {
            $form->fieldChange('fix', '定时发送', $form)
                ->options([0 => '否', 1 => '是'])
                ->default(1)
                ->required()
                ->callablePreCommon(function (Form $form){
                })->callableMap([
                    0 => function (Form $form) {
                    },
                    1 => function (Form $form) {
                        $form->datetime('send_time', '发送时间')
                            ->default(date('Y-m-d H:i:s', strtotime('+30 minutes')))
                            ->help('发送时间至少要大于当前时间半个小时「>30分钟」');
                    }
                ]);
        }
        $user_list = Member::getUsers(User::getOfficeUidFromServerConf() ?: User::OFFICE_UID);
        $from_users = [];
        foreach ($user_list as $user) {
            $from_users[$user['uid']] = $user['nick'];
        }
        $form->select('send_user', '发送人')->options($from_users)->required();
        $form->html("<span style='color:red;'>注意：为避免给用户造成过多打扰，官号【好好住、好好住导游、成长小助手、好好住星探】一天只允许给同一用户发送一条私信！</span>");
        $form->text('push_title', '推送标题')->placeholder('你收到一条私信');

        $form->userProfile('user_profile', '用户分群')
            ->options(\Doraemon\service\position\UserProfileModule::$other_position_rules)
            ->generate();
        $form->divider();
        $form->html($this->htmlTpl1())->plain();
        if ($id) {
            for ($i=0;$i<$row['msg_num'];$i++) {
                $form->html($this->htmlTpl5($i))->plain();
                $form->fieldChange("con_type_$i", '发送类型', $form)
                    ->options(AdmMsgSendDetails::CON_TYPE)
                    ->callablePreCommon(function (Form $form){
                    })->callableMap([
                        AdmMsgSendDetails::CON_TYPE_TEXT => function (Form $form) use($i) {
                            $form->textarea("content_$i", '发送内容');
                        },
                        AdmMsgSendDetails::CON_TYPE_IMAGE => function (Form $form) use($i) {
                            $form->imgUpload("pic_id_$i", '上传图片')->help('单图，必须需要上传');
                        },
                        AdmMsgSendDetails::CON_TYPE_IMG_TXT => function (Form $form) use($i) {
                            $form->text("title_$i", '标题');
                            $form->textarea("desc_$i", '描述');
                            $form->imgUpload("cover_img_$i", '图片');
                            $form->display("link_$i", '链接');
                        },
                        AdmMsgSendDetails::CON_TYPE_CARD => function (Form $form) use($i) {
                            $form->text("title_$i", '标题');
                            $form->text("desc_$i", '描述');
                            $form->display("link_$i", '卡片链接');
                            $form->imgUpload("cover_img_$i", '图片');
                            $form->text("button_text_$i", '按钮文字');
                            $form->display("button_link_$i", '按钮链接');
                        },
                        AdmMsgSendDetails::CON_TYPE_DESIGNER_CARD => function (Form $form) use($i) {
                            $form->text("d_uid_$i", '设计师/装企UID')->setWidth(4, 2)->setElementClass("card_uid");
                        }
                    ]);
                $form->html($this->htmlTpl6())->plain();
            }
            $form->html($this->htmlTpl7())->plain();
        } else {
            for ($i=0;$i<10;$i++) {
                $form->html($this->htmlTpl2($i))->plain();
                $form->fieldChange("con_type[$i]", '发送类型', $form)
                    ->options(AdmMsgSendDetails::CON_TYPE)
                    ->default(0)
                    ->callablePreCommon(function (Form $form){
                    })->callableMap([
                        AdmMsgSendDetails::CON_TYPE_TEXT => function (Form $form) use($i) {
                            $form->textarea("content[$i]", '发送内容');
                        },
                        AdmMsgSendDetails::CON_TYPE_IMAGE => function (Form $form) use($i) {
                            $form->imgUpload("pic_id[$i]", '上传图片')->help('单图，必须需要上传');
                        },
                        AdmMsgSendDetails::CON_TYPE_IMG_TXT => function (Form $form) use($i) {
                            $form->text("title[$i]", '标题');
                            $form->textarea("desc[$i]", '描述');
                            $form->imgUpload("cover_img[$i]", '图片');
                            $form->multiLinkSelect("link[$i]", '链接');
                        },
                        AdmMsgSendDetails::CON_TYPE_CARD => function (Form $form) use($i) {
                            $form->text("title[$i]", '标题');
                            $form->text("desc[$i]", '描述');
                            $form->multiLinkSelect("link[$i]", '卡片链接');
                            $form->imgUpload("cover_img[$i]", '图片');
                            $form->text("button_text[$i]", '按钮文字');
                            $form->multiLinkSelect("button_link[$i]", '按钮链接');
                        },
                        AdmMsgSendDetails::CON_TYPE_DESIGNER_CARD => function (Form $form) use($i) {
                            $form->text("d_uid[$i]", '设计师/装企UID')->setWidth(4, 2)->setElementClass("card_uid");
                        }
                    ]);
                $form->html($this->htmlTpl3())->plain();
            }
            $form->html($this->htmlTpl4())->plain();
        }
        if ($id) {
            $form->disableReset();
            $form->disableSubmit();
        } else {
            $form->action(url('admin/im/save'));
        }

        return $content
            ->header('私信群发')
            ->description($header.'发送任务')
            ->breadcrumb(['text' => '私信群发'])
            ->body($tab);
    }

    public function getUserNick(Request $request)
    {
        try {
            $params = $request->all();
            unset($params['_token']);

            $uid = intval($params['uid']);
            if (empty($uid)) {
                return response()->json([
                    'status' => false,
                    'message' => "请输入正确的uid",
                ]);
            }

            $result = Member::getOne($uid);
            if ($result) {
                if (!in_array($result['type'], [Member::AUTH_USER_DESIGNER, Member::AUTH_DECO_COMPANY])) {
                    return response()->json([
                        'status' => false,
                        'message' => "请输入设计师/装企用户UID",
                    ]);
                }
                return response()->json([
                    'status' => true,
                    'message' => "请求成功",
                    'data' => $result
                ]);
            } else {
                return response()->json([
                    'status' => false,
                    'message' => "用户不存在",
                ]);
            }
        } catch (\Exception $e) {
            Log::debug($e->getMessage());
            return response()->json([
                'status' => false,
                'message' => $e->getMessage(),
            ]);
        }
    }

    /**
     * 添加任务
     * @param Request $request
     * @param Content $content
     * @return \Illuminate\Http\RedirectResponse
     */
    public function save(Request $request, Content $content)
    {
        try {
            $params = $request->input();
            unset($params['_token']);
            foreach ($params['con_type'] as $key=>$item) {
                if ($item == AdmMsgSendDetails::CON_TYPE_TEXT) {
                    $textLen = mb_strlen($params['content'][$key]);
                    if ($params['content'][$key] && $textLen > 200) {
                        throw new \Exception('发送文本不能超过200个字符，当前已输入'.$textLen.'个字符');
                    }
                }
                if (in_array($item, [AdmMsgSendDetails::CON_TYPE_IMG_TXT, AdmMsgSendDetails::CON_TYPE_CARD])) {
                    $textLen = mb_strlen($params['desc'][$key]);
                    if ($params['desc'][$key] && $textLen > 200) {
                        throw new \Exception('描述不能超过200个字符，当前已输入'.$textLen.'个字符');
                    }
                }
                if ($item == AdmMsgSendDetails::CON_TYPE_DESIGNER_CARD) {
                    $d_uid = intval($params['d_uid'][$key]);
                    if ($d_uid) {
                        $user_info = Member::getOne($d_uid);
                        if (!in_array($user_info['type'], [Member::AUTH_USER_DESIGNER, Member::AUTH_DECO_COMPANY])) {
                            throw new \Exception('请输入设计师/装企用户UID');
                        }
                    }
                }
            }

            sAdmMsgSend::addIMTask($params);

            $success = new MessageBag([
                'title' => '操作成功'
            ]);
            return redirect(url('/admin/im/index'))->with(compact('success'));
        } catch (\Exception $e) {
            Log::debug($e->getMessage());
            $error = new MessageBag([
                'title' => '操作失败,信息:' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }

    /**
     * 取消任务
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function cancel(Request $request)
    {
        try {
            $id = $request->input('id', 0);
            $row = AdmMsgSendList::getRow(['id'=>$id]);
            if (in_array($row['send_status'],[
                AdmMsgSendList::SEND_STATUS_NO_START,
                AdmMsgSendList::SEND_STATUS_ALREADY_DATA,
                AdmMsgSendList::SEND_STATUS_ERR_DATA,
                AdmMsgSendList::SEND_STATUS_FAILURE
            ])) {
                $saveData = [];
                $saveData['admin_id'] = Admin::user()->id;
                $saveData['send_status'] = AdmMsgSendList::SEND_STATUS_CANCEL;
                AdmMsgSendList::updateData($saveData, ['id'=>$id]);
                AdmMsgSendTask::delTask($id);
            } else {
                throw new \Exception('当前发送状态不允许删除');
            }
            $result = [
                'title' => '任务 ID: ' . $id . ' 取消成功',
                'code' => 1
            ];
        } catch (\Exception $e) {
            $result = [
                'title' => '取消任务失败',
                'code' => 0,
                'msg' => $e->getMessage()
            ];
        }
        return response()->json($result);
    }

    /**
     * 继续发送
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function resend(Request $request)
    {
        try {
            $id = $request->input('id', 0);
            $row = AdmMsgSendList::getRow(['id'=>$id]);
            if ($row['send_status'] == AdmMsgSendList::SEND_STATUS_FAILURE) {
                $remainingUidCount = AdmMsgSendTask::getUidCount($id);
                if ($remainingUidCount == 0) {
                    throw new \Exception('当前任务待发送用户数为0');
                }
                $saveData = [];
                $saveData['admin_id'] = Admin::user()->id;
                $saveData['send_status'] = AdmMsgSendList::SEND_STATUS_ALREADY_DATA;
                AdmMsgSendList::updateData($saveData, ['id'=>$id]);
            } else {
                throw new \Exception('当前任务状态不允许设置继续发送');
            }
            $result = [
                'title' => '设置成功，请耐心等待任务 ID: ' . $id . ' 开始发送',
                'code' => 1
            ];
        } catch (\Exception $e) {
            $result = [
                'title' => '设置失败',
                'code' => 0,
                'msg' => $e->getMessage()
            ];
        }
        return response()->json($result);
    }

    /**
     * 私信消息列表
     * @param Request $request
     * @param Content $content
     * @return Content
     */
    public function msgList(Request $request, Content $content)
    {
        $params = $request->input();
        $page = $request->input("page", 1);
        $pageSize = $request->input("per_page", 10);
        $search = [];
        if (isset($params['from_user_group']) && isset($params['from_user']) && $params['from_user']) {
            if ($params['from_user_group'] == 1) {
                $search['from_nick'] = $params['from_user'];
            } else {
                if (is_numeric($params['from_user'])) {
                    $search['from_uid'] = $params['from_user'];
                }
            }
        }
        if (isset($params['to_user_group']) && isset($params['to_user']) && $params['to_user']) {
            if ($params['to_user_group'] == 1) {
                $search['to_nick'] = $params['to_user'];
            } else {
                if (is_numeric($params['to_user'])) {
                    $search['to_uid'] = $params['to_user'];
                }
            }
        }
        $order = [];
        if (isset($params['_sort']) && $params['_sort']) {
            $order[$params['_sort']['column']] = strtoupper($params['_sort']['type']);
        }

        $list = sAdmMsgSend::getIMMsgList($search, $page, $pageSize, $order);

        $gridModel = new pGridDataModel($list['list'], $list['total'], [
            'perPage' => $pageSize
        ]);
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableCreateButton();

                $grid->filter(function($filter){
                    // 去掉默认的id过滤器
                    $filter->disableIdFilter();
                    $filter->column(1/2, function ($filter) {
                        $filter->group('from_user', function ($group) {
                            $group->equal('UID');
                            $group->equal('昵称');
                        });
                    });
                    $filter->column(1/2, function ($filter) {
                        $filter->group('to_user', function ($group) {
                            $group->equal('UID');
                            $group->equal('昵称');
                        });
                    });
                    $filter->expand();
                });
                $grid->column('message_id', '会话ID');
                $grid->column('from_uid', '发送方')->userBasicInfo();
                $grid->column('to_uid', '接收方')->userBasicInfo();
                $grid->column('message', '消息内容')->display(function ($message) {
                    $message = json_decode($message, true);
                    return "<span style='width:200px;display: inline-block;'>{$message['data']}</span>";
                });
                $grid->column("add_time", '首次发送时间')->display(function ($add_time) {
                    return $add_time ? date("Y-m-d H:i:s", $add_time) : '';
                })->sortable();
                $grid->column("update_time", '最近发送时间')->display(function ($update_time) {
                    return $update_time ? date("Y-m-d H:i:s", $update_time) : '';
                })->sortable();
                $grid->column("first_reply_time", '首次回复时间')->display(function ($first_reply_time) {
                    return $first_reply_time ? date("Y-m-d H:i:s", $first_reply_time) : '';
                })->sortable();
                $grid->column("reply_time", '最近回复时间')->display(function ($reply_time) {
                    return $reply_time ? date("Y-m-d H:i:s", $reply_time) : '';
                })->sortable();
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableEdit();
                    $actions->disableDelete();
                    $template = <<<HTML
<button type="button" class="btn btn-info btn-xs" data-toggle="modal" data-target="#myModal-{$actions->row->id}"><i class="glyphicon glyphicon-eye-open"></i> 查看会话</button>
<div class="modal fade view-msg" id="myModal-{$actions->row->id}" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">聊天记录 <small>[From:{$actions->row->from_uid} -> To:{$actions->row->to_uid}]</small></h4>
      </div>
      <div class="modal-body">
        <div class="row">
          <div class='col-md-8 msg-kj' id="msg-kj-{$actions->row->id}">
            <p class='text-center' style='padding: 13px 0 0;'>
              <a href='javascript:void(0)' class='view_more' id="more-{$actions->row->id}" data-id="{$actions->row->id}">点击查看更多历史消息</a>
              <span class='current_info' id="cur-index-{$actions->row->id}" style="visibility: hidden" data-from-uid='{$actions->row->from_uid}' data-to-uid='{$actions->row->to_uid}'>0</span>
            </p>
            <div class='msg-con' id="msg-con-{$actions->row->id}" style='overflow:hidden;'></div>
          </div>
          <div class="col-md-4 reply-kj">
            {{reply_html}}
            <p class="text-center"><input type="submit" class="btn btn-info reply-btn" data-id="{$actions->row->id}" value="回复" style="width: 46%" /></p>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
HTML;
                    $form = new Form();
                    $from_user_info = Member::getUserInfoNew($actions->row->from_uid);
                    $form->html('<div style="font-size: 12px; margin-left: -53px;"><label>回复账号</label><span class="sender-info">'. ($from_user_info['nick'] ?? $actions->row->from_uid) .'</span></div>');
                    $form->hidden('send_user')->default($actions->row->from_uid);
                    $form->hidden('to_user')->default($actions->row->to_uid);
                    $form->fieldChange("con_type", '类型', $form)
                        ->options([AdmMsgSendDetails::CON_TYPE_TEXT => '文本', AdmMsgSendDetails::CON_TYPE_IMAGE => '图片', AdmMsgSendDetails::CON_TYPE_IMG_TXT => '图文'])
                        ->default(0)
                        ->callablePreCommon(function (Form $form){
                        })->callableMap([
                            AdmMsgSendDetails::CON_TYPE_TEXT => function (Form $form) {
                                $form->textarea("content", '内容');
                            },
                            AdmMsgSendDetails::CON_TYPE_IMAGE => function (Form $form) {
                                $form->imgUpload("pic_id", '上传图片')->help('单图，必须需要上传');
                            },
                            AdmMsgSendDetails::CON_TYPE_IMG_TXT => function (Form $form) {
                                $form->text("title", '标题');
                                $form->textarea("desc", '描述');
                                $form->imgUpload("cover_img", '图片');
                                $form->multiLinkSelect("link", '链接');
                            },
                            AdmMsgSendDetails::CON_TYPE_CARD => function (Form $form) {
                                $form->text("title", '标题');
                                $form->text("desc", '描述');
                                $form->multiLinkSelect("link", '卡片链接');
                                $form->imgUpload("cover_img", '图片');
                                $form->text("button_text", '按钮文字');
                                $form->multiLinkSelect("button_link", '按钮链接');
                            }
                        ]);
                    $form->disableSubmit();
                    $form->disableReset();
                    $template = str_replace("{{reply_html}}", $form->render(), $template);
                    $actions->append($template);
                });
            });

        $tab = new Tab();
        $tab->add('消息列表', $gridList->render(), true);
        $content->row($tab);
        return $content
            ->header('私信群发')
            ->description(' ')
            ->breadcrumb(['text' => '消息列表']);
    }

    public function getMoreMsg(Request $request, Content $content)
    {
        $params = $request->input();
        $msgList = sAdmMsgSend::gethistoryMsgList($params['from_uid'],$params['to_uid'], $params['page']);

        $returnData = [
            'code' => 1,
            'data' => $msgList
        ];
        return json_encode($returnData, JSON_UNESCAPED_UNICODE);
    }

    public function reply(Request $request)
    {
        try {
            $params = $request->input();
            unset($params['_token']);
            if (!in_array($params['send_user'], User::getOfficeUidFromServerConf() ?: User::OFFICE_UID)) {
                $result = [
                    'title' => '回复失败',
                    'code' => 0,
                    'msg' => '非官号不可回复消息'
                ];
            } else {
                //判断是否是黑名单， 并提示
                $banInfo = Ban::getOneRow($params['to_user'], $params['send_user']);
                if (empty($banInfo)) {
                    sAdmMsgSend::replyMsg($params);
                    $result = [
                        'title' => '回复成功',
                        'code' => 1
                    ];
                } else {
                    $result = [
                        'title' => '回复失败',
                        'code' => 0,
                        'msg' => '用户加入黑名单'
                    ];
                }

            }
        } catch (\Exception $e) {
            $result = [
                'title' => '回复失败',
                'code' => 0,
                'msg' => $e->getMessage()
            ];
        }
        return response()->json($result);
    }

    /**
     * js脚本
     * @return string
     */
    private function addScript()
    {
        return <<<SCRIPT
        $('.cancel-send').unbind('click').click(function(){
            var id= $(this).data('id');
            layer.confirm('确定要取消任务 '+id+' 吗？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                let url = '/admin/im/cancel?id=' +  id;
                let params = {};
                $.post(url, params , function (result) {
                    if (result.code == 1) {
                        layer.msg(result.title);
                    } else {
                        layer.msg(result.title + ': ' + result.msg);
                    }
                    setTimeout(function () {
                        parent.window.location.reload();
                    }, 1000);
                });
            });
        });
        $('.resend').unbind('click').click(function(){
            var id= $(this).data('id');
            layer.confirm('确定要继续发送任务 '+id+' 吗？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                let url = '/admin/im/resend';
                let params = {id:id};
                $.post(url, params , function (result) {
                    if (result.code == 1) {
                        layer.msg(result.title);
                    } else {
                        layer.msg(result.title + ': ' + result.msg);
                    }
                    setTimeout(function () {
                        parent.window.location.reload();
                    }, 1000);
                });
            });
        });
        $('button[type=submit]').on('click',function(e){
            e.preventDefault();
            var form = $(this).parents('form');
            layer.confirm('确定要添加群发任务吗？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                //layer.msg("新增成功");
                setTimeout(function () {
                    form.submit();
                }, 500);
            });
        });
        $('#has-many-con').off('click', '.add').on('click', '.add', function () {
            $('.has-many-con-form').eq($('.has-many-con-form:visible').length).show();
            if ($('.has-many-con-form').length == $('.has-many-con-form:visible').length) {
                $(".add-btn").hide();
            }
            return false;
        });
        $('#has-many-con').off('click', '.remove').on('click', '.remove', function () {
            $(this).closest('.has-many-con-form').hide();
            var index = $(this).closest('.has-many-con-form').attr("data-id");
            $("textarea[name='content["+index+"]'").val("");
            $(this).closest('.has-many-con-form').appendTo($(".has-many-con-forms"));
            if ($('.has-many-con-form').length > $('.has-many-con-form:visible').length) {
                $(".add-btn").show();
            }
            return false;
        });
        $('.view-msg').on('show.bs.modal', function (event) {
          $(this).find('.current_info').text(0);
          $(this).find('.msg-con').html('');
          $(this).find('.view_more').trigger('click');
        });
        $('.view_more').on('click',function(){
            var cPage = $(this).siblings('.current_info').text();
            var from_uid = $(this).siblings('.current_info').attr('data-from-uid');
            var to_uid = $(this).siblings('.current_info').attr('data-to-uid');
            let id = $(this).data('id');
            let start_pos = $("#msg-con-"+id).height();
            cPage++;
            $.get("/admin/im/getMoreMsg?page="+(cPage)+'&from_uid='+from_uid+'&to_uid='+to_uid, function(res){
                $(this).siblings('.current_info').text(cPage);
                res = JSON.parse(res);
                if (res.code == 1) {
                    var oHtml = '';
                    $.each(res.data.list,function(idx,obj){
                        oHtml += obj.msg_con;
                    });
                    if (res.data.is_over == 1) {
                        $(this).parent().hide();
                    }
                    if (oHtml == '') {
                        $(this).parent().hide();
                    } else {
                        $(this).parent().siblings(".msg-con").prepend(oHtml);
                    }
                }
                setTimeout(function () {
                    $("#msg-kj-"+id).scrollTop($("#msg-con-"+id).height() - start_pos - 80);
                }, 500);
            }.bind(this));
        });
        $('.reply-btn').unbind('click').click(function(e){
            e.preventDefault();
            var form = $(this).parent().siblings('form');
            let id = $(this).data('id');
            layer.confirm('确定要回复消息吗？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                $.post('/admin/im/reply', form.serialize() , function (result) {
                    if (result.code == 1) {
                        form[0].reset()
                        layer.msg(result.title);
                        setTimeout(function () {
                            $("#cur-index-"+id).text(0);
                            $("#msg-con-"+id).html('');
                            $('#more-'+id).trigger('click');
                        }, 1000);
                    } else {
                        layer.open({'title':result.title, 'content':result.msg});
                    }
                });
            });
        });
        $(".card_uid").focusout(function(){
            let uid = $(this).val();
            var target = $(this).closest('.form-group');
            $(target).find("b").remove();
            if (uid != "") {
                $.get("/admin/im/user_nick?uid="+uid, function(r){
                    if (r.status) {
                        if (r.data.status == 1) {
                            $(target).append("<b style='line-height: 34px;'>昵称："+ r.data.nick +"</b>");
                        }
                    } else {
                        $(target).append("<b style='line-height: 34px;color: red;'>"+ r.message +"</b>");
                    }
                });
            }
        });
SCRIPT;
    }

    private function addStyle()
    {
        return <<<STYLE
        .msg-kj{border: 1px solid #eee;padding: 0 1rem;height:500px; overflow:scroll;padding-bottom: 18px;border-radius: 1rem;margin-left: 10px;}
        .msg-row{padding: 1rem;border-radius: 1rem;margin-top: 18px;}
        .reply-kj{padding: 0;max-width: 287px;}
        .reply-kj label.control-label{font-size:12px;width:56px;padding:7px 0 0 0;}
        .reply-kj label.radio-inline{font-size:12px;}
        .reply-kj .file-drop-zone-title{padding: 16px 0;font-size: 12px;}
        .reply-kj .krajee-default.file-preview-frame{max-width:100%;padding:0;margin:0;}
        .reply-kj .krajee-default.file-preview-frame .kv-file-content{max-width:100%;height:auto;width:auto;}
        .reply-kj .col-sm-8{width: 239px;padding: 0 14px;}
        .reply-kj .file-preview{padding: 0;}
        .reply-kj textarea{min-height: 100px;font-size: 12px;padding: 8px;border-radius: 3px;}
        .sender-info {display: inline-block;border: 1px solid #d2d6de;margin-left: 5px;padding: 6px 7px;width: 209px;border-radius: 3px;background: #eee;}
STYLE;
    }

    private function htmlTpl1()
    {
        return <<<HTML
        <div class="row">
            <div class="col-sm-2"><h4 class="pull-right">消息内容</h4></div>
            <div class="col-sm-8"></div>
        </div>
        <hr style="margin-top: 0px;">
        <div id="has-many-con" class="has-many-con">
            <div class="has-many-con-forms"> 
HTML;
    }
    private function htmlTpl2($i)
    {
        return <<<HTML
        <div class="has-many-con-form fields-group" data-id="$i" style="display: none;">
HTML;
    }
    private function htmlTpl3()
    {
        return <<<HTML
            <div class="form-group">
                <label class="col-sm-2 control-label"></label>
                <div class="col-sm-8">
                    <div class="remove btn btn-warning btn-sm pull-right"><i class="fa fa-trash"></i>&nbsp;移除</div>
                </div>
            </div>
            <hr>
        </div>
HTML;
    }
    private function htmlTpl4()
    {
        return <<<HTML
        </div>
        <div class="form-group add-btn">
            <label class="col-sm-2 control-label"></label>
            <div class="col-sm-8">
                <div class="add btn btn-success btn-sm"><i class="fa fa-save"></i>&nbsp;新增</div>
            </div>
        </div>
    </div>
HTML;
    }
    private function htmlTpl5($i)
    {
        return <<<HTML
        <div class="has-many-con-form fields-group" data-id="$i">
HTML;
    }
    private function htmlTpl6()
    {
        return <<<HTML
            <hr>
        </div>
HTML;
    }
    private function htmlTpl7()
    {
        return <<<HTML
            </div>
        </div>
HTML;
    }

}